package handlers

import (
	"data_service/models"
	"data_service/server"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 初始化游戏业务服务
var gameService = server.NewGameService()

// CreateGameRoomHandler 创建游戏房间
func CreateGameRoomHandler(c *gin.Context) {
	var req struct {
		Name     string `json:"name" binding:"required"`
		RoomID   string `json:"room_id" binding:"required"`
		GameType string `json:"game_type"`
		Players  string `json:"players"` // JSON数组字符串
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}
	room := &models.GameRoom{
		Name:     req.Name,
		RoomID:   req.RoomID,
		GameType: req.GameType,
		Status:   "waiting",
		Players:  req.Players,
	}
	if err := gameService.CreateGameRoom(room); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建游戏房间失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"room_id": room.RoomID, "game_type": room.GameType})
}

// GetGameRoomsHandler 获取所有游戏房间
func GetGameRoomsHandler(c *gin.Context) {
	rooms, err := gameService.GetGameRooms()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取游戏房间失败"})
		return
	}
	c.JSON(http.StatusOK, rooms)
}

// UpdateGameRoomStatusHandler 更新游戏房间状态
func UpdateGameRoomStatusHandler(c *gin.Context) {
	roomID := c.Query("room_id")
	status := c.Query("status")
	if roomID == "" || status == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}
	if err := gameService.UpdateGameRoomStatus(roomID, status); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新状态失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "状态更新成功"})
}
